require 'Sockets/HTTPSocket'
require 'rexml/document'

class FlickClient
	FLICKR_HOST = 'api.flickr.com'
	FLICKR_PORT = 80
	FLICKR_KEY = '0f8123e52f601560f3eb7c0c0c790b8a'
	FLICKR_SECRET = 'c976a90f5a682f6b'

   def initialize()
	@hsFlickSock = HTTPSocket::new(FLICKR_HOST,FLICKR_PORT)
	@hsFlickSock.AddHeader("User-Agent", "TwitClient/Ruby")
   end

   def GetImagesByTag(sTag)
	sBody = @hsFlickSock.GetURL('/services/rest/?method=flickr.photos.search&api_key=' << FLICKR_KEY << '&tags=' << sTag)
	xdData = REXML::Document.new(sBody)
	
	aImages = Array.new
	xdData.elements.each('rsp/photos/photo'){ |xnNode|
		sFarm = xnNode.attributes['farm']
		sServer = xnNode.attributes['server']
		sId = xnNode.attributes['id']
		sSecret = xnNode.attributes['secret']
		aImages << {'farm'=>'farm'<<sFarm<<'.static.flickr.com','image'=>'/'<<sServer<<'/'<<sId<<'_'<<sSecret<<'_b.jpg'}
	}
	
	return aImages
   end

   def ExtractImage(xaApp,hDetails)
	if(hDetails==nil)
		puts 'RETURNING NULL'
		return nil
	end
	hsImgSock = HTTPSocket::new(hDetails['farm'],FLICKR_PORT)
	sImgData = hsImgSock.GetURL(hDetails['image'])
	if(sImgData.length > 326)
		imImage = FXJPGImage.new(xaApp, sImgData)
		imImage.scale(800,600)
		imImage.create
		return imImage
	end
	#return nil
   end
end